<template>
  <div class="scrollTop" v-show="showTop" @click="toTop">
    <i class="iconfont icon-fanhuidingbu"></i>
  </div>
</template>
<script>
export default {
  data() {
    return {
      scrollTop: 0,
      time: 0,
      dParams: 20,
      scrollState: 0,
    };
  },
  computed: {
    showTop() {
      const value = this.scrollTop > 200;
      return value;
    },
  },
  mounted() {
    window.addEventListener('scroll', this.getScrollTop);
  },
  methods: {
    toTop(e) {
      if (this.scrollState) {
        return;
      }
      this.scrollState = 1;
      e.preventDefault();
      const distance = document.documentElement.scrollTop || document.body.scrollTop;
      const _this = this;
      this.time = setInterval(() => { _this.gotoTop(_this.scrollTop - _this.dParams); }, 10);
    },
    gotoTop(distance) {
      this.dParams += 20;
      distance = distance > 0 ? distance : 0;
      document.documentElement.scrollTop = document.body.scrollTop = window.pageYOffset = distance;
      if (this.scrollTop < 10) {
        clearInterval(this.time);
        this.dParams = 20;
        this.scrollState = 0;
      }
    },
    getScrollTop() {
      this.scrollTop = window.pageYOffset || document.documentElement.scrollTop || document.body.scrollTop;
    },
  },

};
</script>
<style scoped>
  .scrollTop {
    position: fixed;
    right: 1rem;
    bottom: 2.8rem;
    cursor: pointer;
  }
  .scrollTop i{
    font-size: 3.5rem;
    color: #3190e8;
  }
</style>
